package ems;

import entity.Emp;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author:石小俊
 * @Date:2022/12/12 13:57
 * @Version:1.0-SNAPSHOT
 * @Description:
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String path = request.getServletPath();
        if("/add.emp".equals(path)){
            addEmp(request,response);
        } else if("/findAll.emp".equals(path)){
            findAll(request,response);
        } else if("/findById.emp".equals(path)){
            findById(request,response);
        } else if("/modify.emp".equals(path)){
            modifyEmp(request,response);
        } else if("/delete.emp".equals(path)){
            deleteEmp(request,response);
        } else{
            PrintWriter out = response.getWriter();
            out.print("<h1 style='color:red;'>您输入的请求有误,请重新输入</h1>");
        }

    }

    public void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();
            conn.commit();

            // 重定向
            response.sendRedirect(request.getContextPath()+"findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");

        Connection conn = null;
        PreparedStatement ps = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6,Integer.parseInt(id));
            ps.executeUpdate();
            conn.commit();

            // 重定向
            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Emp emp = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            while(rs.next()){
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
            }
            conn.commit();

            // 将emp存储到request中
            request.setAttribute("emp",emp);
            request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 后端服务处理业务数据
        // 处理完成之后将业务数据传递到前端
        // 前端拿到数据之后再页面中展现出来
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8","root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emps.add(emp);
            }

            // 此时后端已经获取到所有的员工数据:emps
            // 需要将emps传递到前端进行处理
            // 向当前请求中存储数据
            // 存值:request.setAttribute("key",value);
            // 取值:request.getAttribute("key")
            // 向request中存储了一条数据
            // 数据的key为:emps,数据的值为对象集合
            request.setAttribute("emps",emps);
            // 此时的数据需要在jsp页面中获取
            // 因此,必须保证当前Servlet与对应的jsp共享request
            // 此时必须使用转发
            // 转发使用绝对路径时的/表示应用名后面的/
            request.getRequestDispatcher("/ems/empList.jsp").forward(request,response);

            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(ps != null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:"+name+",salary:"+salary+",gender:"+gender+",edu:"+edu+",hobbies:"+ Arrays.toString(hobbies));

        // JDBC操作
        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/web?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            conn.setAutoCommit(false);
            String sql = new StringBuffer()
                    .append("insert into ")
                    .append(" t_emp ")
                    .append("   (name,salary,gender,edu,hobbies)")
                    .append(" values ")
                    .append("   (?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setDouble(2,Double.parseDouble(salary));
            ps.setString(3,gender);
            ps.setString(4,edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            // 执行sql
            ps.executeUpdate();
            conn.commit();
            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            request.setAttribute("empMsg",e.getMessage());
            request.getRequestDispatcher("/ems/addEmp.jsp").forward(request,response);
        } finally {

        }
    }

}
